<template>
  <div class="employees-container">
    <!-- 页头 -->
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总条数 {{ total }} </span>
        </template>

        <template #right>
          <el-button type="primary" size="small" @click="$router.push('/import?type=user')">导入员工</el-button>
          <el-button type="primary" size="small" @click="handleDownload">导出</el-button>
          <el-button type="primary" size="small" @click="openDialog">添加员工</el-button>
        </template>
      </page-tools>
    </div>
    <div v-loading="loading" class="app-container">
      <el-card style="margin-top: 10px;">
        <el-table border :data="woker">
          <el-table-column label="序号" :index="indexMethod" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="姓名" prop="username">
            <template #default="{row}">
              <img v-imgerror="defaultImg" :src="row.staffPhoto || defaultImg" alt="" class="img">
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column
            label="聘用形式"
            prop="formOfEmployment"
            :formatter="formatEmployment"
          />
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry">
            <template #default="{row}">
              {{ formatTime(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="showRole(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="del(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-pagination
          :current-page="page"
          :page-sizes="[2, 4, 6, 8]"
          :page-size="size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-card>
    </div>
    <addEmployeeVue :show-dialog.sync="showDialog" />
    <assignRole ref="assignRole" :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
  </div>
</template>

<script>
import employees from '@/constant/employees'
import { getWorkerAPI, delWokerAPI } from '@/api/employees'
import dayjs from 'dayjs'
import defaultImg from '@/assets/common/bigUserHeader.png'
import addEmployeeVue from './components/add-employee.vue'
import assignRole from './components/assign-role.vue'
// 枚举值
// import Employees from '@/constant/employees'
export default {
  name: 'Employees',
  components: {
    addEmployeeVue,
    assignRole
  },
  data() {
    return {
      page: 1,
      size: 4,
      woker: [],
      total: 0,
      loading: false,
      showDialog: false,
      defaultImg: defaultImg,
      showRoleDialog: false,
      userId: ''
    }
  },
  created() {
    this.getWorker()
  },
  methods: {
    showRole(id) {
      this.showRoleDialog = true
      this.userId = id
    },
    handleDownload() {
      import('@/vendor/Export2Excel').then(async(excel) => {
        const headersArr = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
        const headersRelations = {
          '姓名': 'username',
          '手机号': 'mobile',
          '入职日期': 'timeOfEntry',
          '聘用形式': 'formOfEmployment',
          '转正日期': 'correctionTime',
          '工号': 'workNumber',
          '部门': 'departmentName'
        }
        const { data } = await getWorkerAPI(1, this.total)
        const list = []
        data.rows.forEach(item => {
          const tempArr = []
          headersArr.forEach(header => {
            const englishKey = headersRelations[header]
            tempArr.push(item[englishKey])
          })
          list.push(tempArr)
        })
        excel.export_json_to_excel({
          header: headersArr,
          data: list,
          filename: '员工信息',
          autoWidth: true,
          bookType: 'xlsx'
        })
      })
    },
    openDialog() {
      this.showDialog = true
    },
    // 处理表格时间
    formatTime(val) {
      return val ? dayjs(val).format('YYYY-MM-DD') : ''
    },
    del(id) {
      this.$confirm('确认要删除吗', '警告').then(async() => {
        await delWokerAPI(id)
        if (this.woker.length === 1 && this.page > 1) {
          this.page--
        }
        this.$message.success('坏家伙')
        this.getWorker()
      }).catch(() => {})
    },
    formatEmployment(row, column, cellValue) {
      const hireType = employees.hireType
      const obj = hireType.find(item => item.id === +cellValue)
      return obj ? obj.value : '未知'
    },
    async getWorker() {
      this.loading = true
      const { data } = await getWorkerAPI({ page: this.page, size: this.size })
      this.woker = data.rows
      this.total = data.total
      this.loading = false
    },
    handleSizeChange(val) {
      this.size = val
      this.getWorker()
    },
    handleCurrentChange(val) {
      this.page = val
      this.getWorker()
    },
    indexMethod(index) {
      return this.size * (this.page - 1) + index + 1
    }
  }
}
</script>

<style scoped>
.img{
  width: 80px;
  height: 80px;
}

</style>
